package com.pengzy.gateway.filter;

import com.pengzy.comment.core.constant.SecurityConstant;
import com.pengzy.comment.core.enums.PrErrorEnum;
import com.pengzy.comment.core.enums.SecurityEnum;
import com.pengzy.comment.core.jwt.JwtUtil;
import com.pengzy.comment.web.exception.CustomException;
import com.pengzy.comment.web.redis.RedisCache;
import com.pengzy.comment.web.result.JsonResult;
import com.pengzy.comment.web.result.ServletUtils;
import com.pengzy.core.conf.IgnoreUrlsConfig;
import com.pengzy.supports.dto.LoginUserDetails;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.security.sasl.AuthenticationException;
import java.net.URI;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@Order(1)
public class GatewayGlobalFilter implements GlobalFilter, Ordered {


    @Autowired
    private RedisCache redisCache;


    private  final String TOKEN="token";

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("进入网关......");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response=exchange.getResponse();
        URI uri = request.getURI();
        PathMatcher pathMatcher = new AntPathMatcher();
        request = exchange.getRequest()
                .mutate()
                .build();
        exchange = exchange.mutate().request(request).build();

        //白名单路径直接放行
        List<String> ignoreUrls = ignoreUrlsConfig.getUrls();
        for (String ignoreUrl : ignoreUrls) {
            if (pathMatcher.match(ignoreUrl, uri.getPath())) {
                return chain.filter(exchange);
            }
        }
        //对应跨域的预检请求直接放行
        if(request.getMethod()== HttpMethod.OPTIONS){
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        if (!StringUtils.hasText(token)) {
            //放行
            return ServletUtils.writeResponse(response, JsonResult.error(PrErrorEnum.ERROR_1004));
        }
        if(!JwtUtil.venJwt(token)){
            return ServletUtils.writeResponse(response, JsonResult.error(PrErrorEnum.ERROR_1003));
        }
        // 传递给其他微服务
        request = exchange.getRequest()
                .mutate()
                .header(SecurityConstant.TOKEN, token)
                .build();
        exchange = exchange.mutate().request(request).build();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
